<?php

class PostsController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = 'column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        $controller = Yii::app()->getController()->id;
        $action = Yii::app()->getController()->action->id;
        $access = $this->checkAccess($controller, $action);
        return array(
            array($access,
                'actions' => array($action),
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Posts;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Posts'])) {

            $model->attributes = $_POST['Posts'];
            if ($model->save()) {

                if (!empty($_POST['resourcesName'])) {
                    //保存附件
                    $resourcesModel = new PostResources;
                    foreach ($_POST['resourcesName'] as $key => $val) {
                        $resourcesModel->unsetAttributes();
                        $resourcesModel->setIsNewRecord(true);
                        $resourcesModel->attributes = array(
                            'post_id' => $model->id,
                            'file_name' => $val,
                            'file_url' => $_POST['resourcesUrl'][$key],
                        );
                        $resourcesModel->save();
                    }
                }

                $this->redirect(array('view', 'id' => $model->id));
            }
        }
        $category = Categorys::model()->findByPk((int) $_GET['category_id']);

        $model->post_date = date('Y-m-d H:i:s');
        $this->render('create', array(
            'model' => $model,
            'category' => $category,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Posts'])) {
            $model->attributes = $_POST['Posts'];
            if ($model->save()) {
                if (!empty($_POST['resourcesName'])) {
                    //保存附件
                    $resourcesModel = new PostResources;
                    foreach ($_POST['resourcesName'] as $key => $val) {
                        $resourcesModel->unsetAttributes();
                        $resourcesModel->setIsNewRecord(true);
                        $resourcesModel->attributes = array(
                            'post_id' => $model->id,
                            'file_name' => $val,
                            'file_url' => $_POST['resourcesUrl'][$key],
                        );
                        $resourcesModel->save();
                    }
                }
                $this->redirect(array('view', 'id' => $model->id));
            }
        }
        $category = Categorys::model()->findByPk($model->category_id);

        $this->render('update', array(
            'model' => $model,
            'category' => $category
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $category = array();
        if (isset($_GET['category_id'])) {
            $category = Categorys::model()->findByPk((int) $_GET['category_id']);
            if ($category->category_type == 'page' || $category->category_type == 'link')
                $this->redirect($this->createUrl('categorys/update', array('id' => $category->id)));
        }
        $model = new Posts('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Posts']))
            $model->attributes = $_GET['Posts'];
        if (!empty($category)) {
            $model->category_id = $category->id;
        }
        //栏目
        $categoryModel = new Categorys;
        $categorys = $categoryModel->getCategorysArray();
        //print_r($categorys);
        $this->render('admin', array(
            'model' => $model,
            'categorys' => $categorys,
            'category' => $category,
        ));
    }

    public function actionAjax() {
        if (Yii::app()->request->isAjaxRequest) {
            switch($_POST['action'])
            {
                case 'deleteResource':
                    $id = (int)$_POST['id'];
                    echo PostResources::model()->deleteByPk($id);
                    break;
            }
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Posts::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'posts-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
